﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using EzDesk.Utility.Log;

namespace EzDesk.Utility.TimerService
{
    public class TimerServiceHost
    {
        #region [ Singleton Constructor ] 
        private TimerServiceHost() { }
        public static readonly TimerServiceHost Instance = new TimerServiceHost();
        #endregion

        private static readonly Object LockObj = new object();

        private readonly List<ITimerTask> _timerTasks = new List<ITimerTask>();
        private Timer _timer;
        private const int Period = 3000;


        public TimerServiceHost Begin()
        {
            _timer = new Timer(ExecuteTimerTasks, null, 500, Period);
            return this;
        }

        public TimerServiceHost End()
        {
            _timer.Dispose();
            return this;
        }

        private void ExecuteTimerTasks(object state)
        {
            DateTime now = DateTime.Now;
            LogEx.WriteEventLog("开始执行定时服务   " + now);

            foreach (var timerTask in _timerTasks.ToList())
            {
                try
                {
                    ExecuteSingleTask(timerTask,now);
                }
                catch (Exception ex)
                {
                    LogEx.WriteEventLog("开始执行任务  " + timerTask.GetType());
                    //TODO: Write log here.
                    lock (TimerServiceHost.LockObj)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(ex.Message);
                    }
                    continue;
                }

            }
        }

        private static void ExecuteSingleTask(ITimerTask timerTask,DateTime now)
        {
            double diff = (now - timerTask.ExecuteTime).TotalMilliseconds;
            LogEx.WriteEventLog("检测执行任务条件 --   " + timerTask.GetType());
            if (diff >= 0 && diff < Period && timerTask.CanExecute())
            {
                LogEx.WriteEventLog("开始执行任务  " + timerTask.GetType());
                ThreadPool.QueueUserWorkItem(timerTask.Execute);
            }
        }

        public TimerServiceHost RegistTask(ITimerTask timerTask)
        {
            var existedTask = _timerTasks.Where(t => t.TaskName == timerTask.TaskName);
            if (existedTask.Count() > 0)
            {
                // todo: 重复错误处理
                LogEx.WriteEventLog("添加重复的TimerTask  " + timerTask.GetType());
                
            }
            else
            {
                _timerTasks.Add(timerTask);
                LogEx.WriteEventLog("添加任务:  " + timerTask.GetType());
            }
            return this;
        }
        public TimerServiceHost Remove(string taskName)
        {
            _timerTasks.RemoveAll(t => t.TaskName == taskName);
            LogEx.WriteEventLog("删除任务:  " + _timerTasks.GetType());
            return this;
        }
        public TimerServiceHost Clear()
        {
            _timerTasks.Clear();
            LogEx.WriteEventLog("清空所有任务");
            return this;
        }

    }
}
